package org.goodprinciples.commons.command.handler;

import org.apache.log4j.Logger;
import org.goodprinciples.commons.command.Command;
import org.goodprinciples.commons.command.DataAccessCommand;
import org.goodprinciples.commons.command.ReportCommand;
import org.goodprinciples.commons.command.exception.CommandException;
import org.goodprinciples.commons.dao.DAOFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Francesco Conte
 */
public class LocalCommandHandler<F extends DAOFactory> implements CommandHandler<F> {
    
    private static Logger logger = Logger.getLogger(LocalCommandHandler.class);
    
    private F factory = null;

    @Override
    public void setDAOFactory(F factory) {
        this.factory = factory;
    }

    @Override
    @Transactional(propagation=Propagation.NEVER)
    public void execute(Command c) throws CommandException {
        try {
            c.execute();
        } catch(Throwable t) {
            logger.error("", t);
            throw new CommandException(t);
        }
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public void execute(DataAccessCommand dac) throws CommandException {
        try {
            dac.setDaoFactory(factory);
            dac.execute();
        } catch(Throwable t) {
            logger.error("", t);
            throw new CommandException(t);
        }
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED, readOnly=true)
    public void execute(ReportCommand rc) throws CommandException {
        try {
            rc.setDaoFactory(factory);
            rc.execute();
        } catch(Throwable t) {
            logger.error("", t);
            throw new CommandException(t);
        }
    }
    
}
